package com.tianshuai.gallerypic.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.tianshuai.gallerypic.adapter.ImagePreviewAdapter;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;
import com.yancy.gallerypick.R;

import java.util.ArrayList;
import java.util.List;


public class GalleryPickPreviewActivity extends AppCompatActivity {

    private ViewPager mImgViewPager;
    private ImageView mBackBtn;
    private ImageView ivSelect;
    private TextView tvFinish;
    private RelativeLayout rlTop;
    private RelativeLayout rlBottom;
    private Context mContext;
    private boolean visible = true;
    private boolean selected;
    private ArrayList<String> selectUrls, newSelectUrls;
    private ArrayList<String> urls;
    List<Integer> selectPosition = new ArrayList<>();
    public static int RESULT_CODE = 1;
    private int previewType;

    private GalleryConfig galleryConfig;   // GalleryPick 配置器
    private IHandlerCallBack mHandlerCallBack;  //GalleryPick 生命周期接口
    private ImagePreviewAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gallery_pick_preview_new);
        mContext = this;
        galleryConfig = GalleryPick.getInstance().getGalleryConfig();
        if (galleryConfig == null) {
            exit();
            return;
        }

        mHandlerCallBack = galleryConfig.getIHandlerCallBack();
        mHandlerCallBack.onStart();
        initView();
        initData();
        initListener();
    }

    private void initView() {

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        mBackBtn = super.findViewById(R.id.iv_back);
        ivSelect = super.findViewById(R.id.iv_select);
        mImgViewPager = super.findViewById(R.id.viewPager);
        tvFinish = super.findViewById(R.id.tv_finish);

        rlTop = super.findViewById(R.id.rl_top);
        rlBottom = super.findViewById(R.id.rl_bottom1);
    }

    private void initListener() {
        //返回
        mBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("select", newSelectUrls);
                intent.putExtras(bundle);
                setResult(RESULT_CODE, intent);
                finish();
            }
        });

        //点击勾选
        ivSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (selected){
                    ivSelect.setImageResource(R.mipmap.gallery_pick_select_unchecked);
                    selected = false;
                    if (previewType == 0) {
                        for (int i = 0; i < selectUrls.size(); i++) {
                            if (TextUtils.equals(selectUrls.get(i), urls.get(mImgViewPager.getCurrentItem()))) {
                                newSelectUrls.remove(i);
                                selectPosition.remove(i);
                                break;
                            }
                        }
                    } else {
                        for (int i = 0; i < newSelectUrls.size(); i++) {
                            if (TextUtils.equals(newSelectUrls.get(i), urls.get(mImgViewPager.getCurrentItem()))) {
                                newSelectUrls.remove(i);
                                selectPosition.remove(i);
                                break;
                            }
                        }
                    }
                } else {
                    if (galleryConfig.getMaxSize() <= newSelectUrls.size()){
                        Toast.makeText(mContext, "勾选图片数量已达上限", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    ivSelect.setImageResource(R.mipmap.gallery_pick_select_checked);
                    selected = true;
                    if (previewType == 0){
                        newSelectUrls.add(urls.get(mImgViewPager.getCurrentItem()));
                        selectPosition.add(mImgViewPager.getCurrentItem());
                    } else {
                        newSelectUrls.add(selectUrls.get(mImgViewPager.getCurrentItem()));
                        selectPosition.add(mImgViewPager.getCurrentItem());
                    }
                }
            }
        });

        //点击完成
        tvFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (newSelectUrls != null && newSelectUrls.size() > 0){
                    mHandlerCallBack.onSuccess(newSelectUrls);
                    GalleryPickActivity.galleryPickActivity.finish();
                    exit();
                } else {
                    Toast.makeText(mContext, "请选择图片", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putStringArrayList("select", newSelectUrls);
        intent.putExtras(bundle);
        setResult(RESULT_CODE, intent);
        finish();
    }

    private void initData() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        newSelectUrls = new ArrayList<>();
        if (bundle != null) {
            urls = GalleryPickActivity.photoPath;
            selectUrls = bundle.getStringArrayList("selectUrls");
            previewType = intent.getIntExtra("type", 0);
            int position = intent.getIntExtra("position", 0);
            newSelectUrls.addAll(selectUrls);
            if (previewType == 0) {
                adapter = new ImagePreviewAdapter(mContext, urls);
                for (String url:urls){
                    if (selectUrls.contains(url)){
                        selectPosition.add(urls.indexOf(url));
                    }
                }
            } else {
                adapter = new ImagePreviewAdapter(mContext, selectUrls);
                for (String url:selectUrls){
                    selectPosition.add(selectUrls.indexOf(url));
                }
            }
                mImgViewPager.setAdapter(adapter);
                adapter.setOnPhotoClickListener(new ImagePreviewAdapter.OnCallBack() {
                    @Override
                    public void OnPhotoClick() {
                        if (visible){
                            rlTop.setVisibility(View.GONE);
                            rlBottom.setVisibility(View.GONE);
                            visible = false;
                        } else {
                            rlTop.setVisibility(View.VISIBLE);
                            rlBottom.setVisibility(View.VISIBLE);
                            visible = true;
                        }
                    }
                });
                mImgViewPager.setCurrentItem(position);
                mImgViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                        if (selectPosition.contains(position)){
                            ivSelect.setImageResource(R.mipmap.gallery_pick_select_checked);
                            selected = true;
                        } else {
                            ivSelect.setImageResource(R.mipmap.gallery_pick_select_unchecked);
                            selected = false;
                        }
                    }

                    @Override
                    public void onPageSelected(int position) {
                        if (selectPosition.contains(position)){
                            ivSelect.setImageResource(R.mipmap.gallery_pick_select_checked);
                            selected = true;
                        } else {
                            ivSelect.setImageResource(R.mipmap.gallery_pick_select_unchecked);
                            selected = false;
                        }
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }
        }


    /**
     * 退出
     */
    private void exit() {
        if (mHandlerCallBack != null) {
            mHandlerCallBack.onFinish();
        }
        finish();
    }
}
